import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { BiStatus } from '@/common/type/BiStatus';
import { list, remove, update, get } from './List/service';

export interface Order {
  id: number;
  orderSn: number;
  createTime: string;
  paymentTime: string;
  deliveryTime: string;
  receiveTime: string;
  commentTime: string;
  appUserName: number;
  totalAmount: number;
  payType: BiStatus;
  sourceType: number;
  status: number;
  receiverName: string;
  receiverPhone: string;
  receiverPostCode: string;
  receiverProvince: string;
  receiverCity: string;
  receiverRegion: string;
  receiverDetailAddress: string;
  operations: OrderOperateHistory[];
  orderItems: OrderItem[];
  deliveryCompany: string;
  deliverySn: string;
}

export interface OrderItem {
  id: number;
  productPic: string;
  productName: string;
  price: number;
  productAttr: string;
  quantity: number;
}

export interface OrderOperateHistory {
  id: number;
  orderId: number;
  operateMan: string;
  createTime: string;
  orderStatus: number;
  note: string;
}

export interface OrderModelState {
  orders: Order[];
  orderDetails?: Order;
}

export interface OrderModelType extends Model {
  namespace: 'order';
  state: OrderModelState;
  effects: {
    query: Effect;
    queryOne: Effect;
    remove: Effect;
    update: Effect;
  };
  reducers: {
    reload: Reducer<OrderModelState>;
  };
}

const orderModel: OrderModelType = {
  namespace: 'order',
  state: {
    orders: [],
  },

  reducers: {
    reload(state, action) {
      return {
        ...state,
        orders: action.orders || state?.orders,
        orderDetails: action.orderDetails || state?.orderDetails,
      };
    },
  },

  effects: {
    *query({ _payload }, { call, put }) {
      const data = yield call(list);
      yield put({
        type: 'reload',
        orders: data,
      });
    },
    *queryOne({ id }, { call, put }) {
      const data = yield call(get, id);
      yield put({
        type: 'reload',
        orderDetails: data,
      });
    },
    *remove({ id, callback }, { call, put }) {
      yield call(remove, id);
      yield put({
        type: 'query',
      });
      if (callback) {
        callback();
      }
    },
    *update({ payload, callback }, { call, put }) {
      yield call(update, payload);
      yield put({
        type: 'query',
      });
      yield put({
        type: 'queryOne',
        id: payload.id,
      });
      if (callback) {
        callback();
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        if (pathname.startsWith('/order')) {
          dispatch({
            type: 'query',
          });
        }
        if (pathname.startsWith('/order/details')) {
          dispatch({
            type: 'queryOne',
            id: query.id,
          });
        }
      });
    },
  },
};

export default orderModel;
